import axios from 'axios'

// 创建axios实例
const http = axios.create({
  baseURL: 'http://localhost:8080',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
    'Authorization': localStorage.getItem('token')
  }
})

// 请求拦截器
http.interceptors.request.use(
  config => {
    console.log('发送服务页面请求:', config)
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
http.interceptors.response.use(
  response => {
    console.log('服务页面响应数据:', response)
    // 处理后端返回的数据结构 {code, message, data}
    // 对于服务页面数据API，需要返回data部分
    // 对于其他API，返回完整响应让调用方自己处理
    if (response.config.url && response.config.url.includes('api/services/info')) {
      // 服务页面数据API，返回data部分
      if (response.data && response.data.code === 0) {
        return response.data.data
      }
      return response.data
    }
    // 其他API返回完整响应
    return response.data
  },
  error => {
    console.error('服务页面请求错误:', error)
    return Promise.reject(error)
  }
)

/**
 * 获取服务页面数据
 * @returns {Promise} 服务页面数据
 */
export const getServiceDataApi = () => {
  return http.get('api/services/info').catch(error => {
    console.error('获取服务页面数据失败:', error)
    // 返回模拟数据以确保页面能正常渲染
    // return {
    //   vipServiceList: [
    //     { name: '余额', content: 0 },
    //     { name: '优惠券', content: 4 },
    //     { name: '会员特权', content: 7 },
    //     { name: '会员福利', content: 21 }
    //   ],
    //   homeServiceList: [
    //     { icon: '/src/assets/imgs/my_icon_1.svg', title: '省心搬家' },
    //     { icon: '/src/assets/imgs/my_icon_2.svg', title: '日常保洁' },
    //     { icon: '/src/assets/imgs/my_icon_3.svg', title: '新人专区' },
    //     { icon: '/src/assets/imgs/my_icon_4.svg', title: '家电清洗' },
    //     { icon: '/src/assets/imgs/my_icon_5.svg', title: '维修安装' },
    //     { icon: '/src/assets/imgs/my_icon_6.svg', title: '一站搬家' },
    //     { icon: '/src/assets/imgs/my_icon_7.svg', title: '深度保洁' },
    //     { icon: '/src/assets/imgs/my_icon_8.svg', title: '空调清洗' },
    //     { icon: '/src/assets/imgs/my_icon_9.svg', title: '包年初体验' },
    //     { icon: '/src/assets/imgs/customer.svg', title: '家庭保姆' },
    //     { icon: '/src/assets/imgs/my_icon_1.svg', title: '上门喂猫' },
    //     { icon: '/src/assets/imgs/my_icon_2.svg', title: '新居开荒' },
    //     { icon: '/src/assets/imgs/my_icon_3.svg', title: '精细增菌' },
    //     { icon: '/src/assets/imgs/my_icon_4.svg', title: '洗衣机清洗' },
    //     { icon: '/src/assets/imgs/my_icon_5.svg', title: '更多' }
    //   ],
    //   serviceActivity: {
    //     name: '12.9-12.19',
    //     img: '/src/assets/imgs/service_bg.png',
    //     title: '限享6次礼包',
    //     subTitle: '包年服务好礼享不停\n最高省300优惠券'
    //   },
    //   newcomerZone: {
    //     img: '/src/assets/imgs/discover_bg.png'
    //   },
    //   cleaningServiceInfo: [
    //     {
    //       img: '/src/assets/imgs/room_text_bg.png',
    //       title: '日常保洁2小时',
    //       subTitle: '擦玻璃60+㎡对的房屋',
    //       originalPrice: '¥119',
    //       priceAfterDiscounts: '¥80'
    //     },
    //     {
    //       img: '/src/assets/imgs/room_text_bg.png',
    //       title: '日常保洁3小时',
    //       subTitle: '擦玻璃60+㎡对的房屋',
    //       originalPrice: '¥149',
    //       priceAfterDiscounts: '¥135'
    //     }
    //   ]
    // }
  })
}

/**
 * 创建服务预约
 * @param {Object} bookingData - 预约数据
 * @param {number} bookingData.serviceId - 服务ID
 * @param {string} bookingData.contactName - 联系人姓名
 * @param {string} bookingData.contactPhone - 联系人手机号
 * @param {string} bookingData.address - 服务地址
 * @param {string} bookingData.appointmentDate - 预约日期
 * @param {string} bookingData.appointmentTime - 预约时间
 * @param {string} bookingData.serviceDescription - 服务描述
 * @param {string} bookingData.specialRequirements - 特殊要求
 * @param {number} bookingData.totalPrice - 总价格
 * @returns {Promise<{code: number, message: string, data: any}>}
 */
export const createServiceBookingApi = async (bookingData) => {
  try {
    // 构建符合后端API格式的数据
    const requestData = {
      serviceId: bookingData.serviceId,
      contactName: bookingData.contactName,
      contactPhone: bookingData.contactPhone,
      address: bookingData.address,
      appointmentDate: bookingData.appointmentDate,
      appointmentTime: bookingData.appointmentTime,
      serviceDescription: bookingData.serviceDescription,
      specialRequirements: bookingData.specialRequirements,
      totalPrice: bookingData.totalPrice
    }
    
    console.log('发送服务预约请求:', requestData)
    const response = await http.post('/auth/service/reservation', requestData)
    console.log('API响应原始数据:', response)
    return response
  } catch (error) {
    console.error('创建服务预约失败:', error)
    
    if (error.response) {
      // 服务器返回了错误状态码
      console.error('服务器错误响应:', error.response.data)
      throw new Error(error.response.data.message || '预约失败')
    } else {
      // 网络错误或其他错误
      throw new Error('网络错误，请检查连接')
    }
  }
}

/**
 * 获取用户预约历史
 * @returns {Promise<Array>} 预约列表
 */
export const getServiceBookingHistoryApi = async () => {
  try {
    const response = await http.get('/auth/service/history')
    console.log('预约历史API响应原始数据:', response)
    return response
  } catch (error) {
    console.error('获取服务预约历史失败:', error)
    
    if (error.response) {
      console.error('服务器错误响应:', error.response.data)
      throw new Error(error.response.data.message || '获取预约历史失败')
    } else {
      throw new Error('网络错误，请检查连接')
    }
  }
}

/**
 * 根据状态获取预约列表
 * @param {string} status - 预约状态（可选）
 * @returns {Promise<Array>} 预约列表
 */
export const getServiceBookingListApi = async (status = '') => {
  try {
    const url = status ? `/auth/service/list?status=${encodeURIComponent(status)}` : '/auth/service/list'
    const response = await http.get(url)
    return response
  } catch (error) {
    console.error('获取服务预约列表失败:', error)
    
    if (error.response) {
      throw new Error(error.response.data.message || '获取预约列表失败')
    } else {
      throw new Error('网络错误，请检查连接')
    }
  }
}

/**
 * 获取预约详情
 * @param {number} bookingId - 预约ID
 * @returns {Promise<Object>} 预约详情
 */
export const getServiceBookingDetailApi = async (bookingId) => {
  try {
    const response = await http.get(`/auth/service/detail/${bookingId}`)
    return response
  } catch (error) {
    console.error('获取预约详情失败:', error)
    
    if (error.response) {
      throw new Error(error.response.data.message || '获取预约详情失败')
    } else {
      throw new Error('网络错误，请检查连接')
    }
  }
}

/**
 * 更新预约状态
 * @param {number} bookingId - 预约ID
 * @param {string} status - 新状态
 * @returns {Promise<{code: number, message: string}>}
 */
export const updateServiceBookingStatusApi = async (bookingId, status) => {
  try {
    const response = await http.put(`/auth/service/status/${bookingId}?status=${encodeURIComponent(status)}`)
    return response
  } catch (error) {
    console.error('更新预约状态失败:', error)
    
    if (error.response) {
      throw new Error(error.response.data.message || '更新预约状态失败')
    } else {
      throw new Error('网络错误，请检查连接')
    }
  }
}

/**
 * 取消服务预约
 * @param {number} bookingId - 预约ID
 * @returns {Promise<{code: number, message: string}>}
 */
export const cancelServiceBookingApi = async (bookingId) => {
  try {
    const response = await http.put(`/auth/service/cancel/${bookingId}`)
    return response
  } catch (error) {
    console.error('取消服务预约失败:', error)
    
    if (error.response) {
      throw new Error(error.response.data.message || '取消预约失败')
    } else {
      throw new Error('网络错误，请检查连接')
    }
  }
}

/**
 * 删除服务预约
 * @param {number} bookingId - 预约ID
 * @returns {Promise<{code: number, message: string}>}
 */
export const deleteServiceBookingApi = async (bookingId) => {
  try {
    const response = await http.delete(`/auth/service/${bookingId}`)
    return response
  } catch (error) {
    console.error('删除服务预约失败:', error)
    
    if (error.response) {
      throw new Error(error.response.data.message || '删除预约失败')
    } else {
      throw new Error('网络错误，请检查连接')
    }
  }
}

export default http
